const fs = require('fs');
const path = require('path');

// const crypto = require('crypto');

// function md5(data) {
//   let obj = crypto.createHash('md5');
//   obj.update(data);
//   return obj.digest('hex');
// }

// const pass_key = fs.readFileSync(path.resolve(__dirname, '../password_key.txt')).toString();
// function password(str) {
//   return md5(str + pass_key);
// }

// const pass_key_admin = "dsadskjhfjkjkghkfhwejhfkjh@#1234u234423584975820957#!@$%^%*^&";
// function admin_password(str) {
//   return md5(str + pass_key_admin);
// }

const getToken = () => {
  return fs.readFileSync(path.resolve(__dirname, '../token.txt')).toString();
}
const setToken = (token) => {
  return fs.writeFileSync(path.resolve(__dirname, '../token.txt'), token);
}

function getProcessArg(name) {
  const args = require('minimist')(process.argv.slice(2))
  return args[name]
}

const uuidLib = require('uuid');
function uuid() {
  return uuidLib.v4().replace(/\-/g, '');
}

function parseTree(arr) {
  const lv1 = []
  const lv2 = []
  arr = arr.map(item => JSON.parse(item))

  arr.forEach(item => {
    if (item.level === 1) {
      lv1.push(item)
    } else {
      lv2.push(item)
    }
  })
  lv1.forEach(item => {
    // if (item.id !== 1) {
    //   return
    // }
    item.children = []
    lv2.forEach(i => {
      if (item.id === i.parentId) {
        item.children.push(i)
      }
    })
  })
  return lv1
}

module.exports = {
  parseTree,
  getProcessArg,
  getToken,
  setToken,
  // md5,
  // password, admin_password,
  uuid
};
